/**
 * 
 */
package vn.smartware.co.framework.plugin;

import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import vn.smartware.co.framework.config.PropertyResources;
import vn.smartware.co.framework.exception.ClientException;
import vn.smartware.co.java.net.commons.Const;
import vn.smartware.co.java.net.commons.Utils;

/**
 * SystemConfig
 */
public class LangResources implements Serializable {

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 729620562033174488L;

	private static Log log = LogFactory.getLog(LangResources.class);
	
	private static LangResources langResources;
	
	/**
	 * getInstance
	 * @return SystemResources
	 */
	public static LangResources getInstance(){
		
		if (Utils.isNullEmpty(langResources)){
			try {
				String langFile = SystemResources.getInstance().getLanguageFile();
				langResources = readLangResources(langFile);
				
			} catch (Exception e) {
				log.error("LangResources getInstance Exception", e);
				e.printStackTrace();
			}
		}
		return langResources;
	}
	
    /**
	 * read language resource
	 */
    private static LangResources readLangResources(String file)
			throws IOException, ClientException {
		
    	LangResources lang = new LangResources();
    	
    	Properties prop = null;
    	
		ClassLoader loader = LangResources.class.getClassLoader();
		
		InputStream is = loader.getResourceAsStream(file);

		if (is == null) {
			throw new ClientException(file + " is NotFound.");
		}
		
		prop = PropertyResources.getProperties(file, is);
				
		lang.setProps(prop);
		
		return lang;
	}
    
	private Properties props;
	
	/**
	 * @return the props
	 */
	public Properties getProps() {
		return props;
	}

	/**
	 * @param props the props to set
	 */
	public void setProps(Properties props) {
		this.props = props;
	}
    
	/**
	 * get text for control
	 * @param key
	 * @return String
	 */
	public static String getText(String key){
		if (Utils.isNullEmpty(langResources)){
			try {
				String langFile = SystemResources.getInstance().getLanguageFile();
				langResources = readLangResources(langFile);
				
			} catch (Exception e) {
				log.error("LangResources getInstance Exception", e);
				e.printStackTrace();
			}
		}
		if (Utils.isNullEmpty(key)) {
			return Const.BLANK;
		}
		return langResources.props.getProperty(key);
	}
	
	/**
	 * get current displaying language
	 * @return String
	 */
	public static String getCurrentLanguage(){
		return SystemResources.getInstance().getCurrentLanguage();
	}
	
	/**
	 * get support languages
	 * @return String
	 */
	public static String[] getSupportLanguage(){
		return SystemResources.getInstance().getSupportLanguages();
	}
}
